<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     <el-form-item label="薪酬周期" prop="payPeriod">
          <el-date-picker
            clearable
            v-model="queryParams.payPeriod"
            type="month"
            value-format="yyyy-MM"
            placeholder="请输入薪酬周期">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes/rl:salary:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes/rl:salary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes/rl:salary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes/rl:salary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="员工姓名" align="center" prop="employeeName" />
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="薪酬周期" align="center" prop="payPeriod" />
      <el-table-column label="基本工资" align="center" prop="baseSalary" />
      <el-table-column label="绩效工资" align="center" prop="commission" />
      <el-table-column label="加班费" align="center" prop="overtimePay" />
      <el-table-column label="奖金" align="center" prop="bonus" />
      <el-table-column label="津贴" align="center" prop="allowance" />
      <el-table-column label="应发工资" align="center" prop="grossSalary" />
      <el-table-column label="社会保险" align="center" prop="socialInsurance" />
      <el-table-column label="医疗保险" align="center" prop="medicalInsurance" />
      <el-table-column label="公积金" align="center" prop="housingFund" />
      <el-table-column label="个税" align="center" prop="taxAmount" />
      <el-table-column label="扣款" align="center" prop="deductions" />
      <el-table-column label="实发工资" align="center" prop="netSalary" />
<!--      <el-table-column label="税率" align="center" prop="taxRate" />-->
      <el-table-column label="支付日期" align="center" prop="paymentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="paymentMethod" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rl_salary_payment" :value="scope.row.paymentMethod"/>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="notes" />
      <el-table-column label="薪酬状态" fixed="right" align="center" prop="salaryStatus" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.salaryStatus === '已支付'"  type="success">已支付</el-tag>
          <el-tag v-if="scope.row.salaryStatus === '未支付'"  type="danger">未支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.salaryStatus == '未支付'">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:wm:pandian:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.salaryStatus == '未支付'">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mes/rl:salary:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改薪酬管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="width: 100%">

          <el-input v-model="form.employeeId" type="hidden" placeholder="请输入员工姓名"  />
        <el-row :gutter="20">
          <el-col :span="12">
<!--            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
            </el-form-item>-->
            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="form.employeeName" :disabled="true" placeholder="请选择员工" >
                <el-button slot="append" @click="handleUserSelect"  icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptName">
              <el-input v-model="form.deptName" :disabled="true" placeholder="请输入内容" />
<!--              <treeselect v-model="form.deptId" :options="deptOptions" @select="selectDept" :show-count="true" placeholder="请选择归属部门" />-->
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="薪酬周期" prop="payPeriod">
              <!--          <el-input v-model="form.payPeriod" placeholder="请输入薪酬周期" />-->
              <el-date-picker
                clearable
                v-model="form.payPeriod"
                type="month"
                value-format="yyyy-MM"
                placeholder="请输入薪酬周期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪酬状态">
              <!--              <el-input v-model="form.salaryStatus" placeholder="薪酬状态" />-->
              <el-select v-model="form.salaryStatus" placeholder="请选择薪酬状态"  style="width: 100%;" clearable>
                <el-option label="未支付" value="未支付" ></el-option>
                <el-option label="已支付" value="已支付"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="基本工资" prop="baseSalary" >
              <!--          <el-input type="number"  v-model.number="form.baseSalary" placeholder="请输入基本工资" />-->
              <el-input-number v-model="form.baseSalary" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绩效工资" prop="commission">
<!--              <el-input v-model="form.commission" placeholder="绩效工资" />-->
              <el-input-number v-model="form.commission" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="加班费" prop="overtimePay">
<!--              <el-input v-model="form.overtimePay" placeholder="请输入加班费" />-->
              <el-input-number v-model="form.overtimePay" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="奖金" prop="bonus">
<!--              <el-input v-model="form.bonus" placeholder="请输入奖金" />-->
              <el-input-number v-model="form.bonus" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="津贴" prop="allowance">
<!--              <el-input v-model="form.allowance" placeholder="请输入津贴" />-->
              <el-input-number v-model="form.allowance" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应发工资" prop="grossSalary">
<!--              <el-input v-model="form.grossSalary" placeholder="请输入应发工资" />-->
              <el-input-number v-model="form.grossSalary" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="社会保险" prop="socialInsurance">
<!--              <el-input v-model="form.socialInsurance" placeholder="请输入社会保险" />-->
              <el-input-number v-model="form.socialInsurance" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医疗保险" prop="medicalInsurance">
<!--              <el-input v-model="form.medicalInsurance" placeholder="请输入医疗保险" />-->
              <el-input-number v-model="form.medicalInsurance" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公积金" prop="housingFund">
<!--              <el-input v-model="form.housingFund" placeholder="请输入公积金" />-->
              <el-input-number v-model="form.housingFund" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个税" prop="taxAmount">
<!--              <el-input v-model="form.taxAmount" placeholder="请输入个税" />-->
              <el-input-number v-model="form.taxAmount" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="扣款" prop="deductions">
<!--              <el-input v-model="form.deductions" placeholder="请输入扣款" />-->
              <el-input-number v-model="form.deductions" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实发工资" prop="netSalary">
<!--              <el-input v-model="form.netSalary" placeholder="请输入实发工资" />-->
              <el-input-number v-model="form.netSalary" :percision="2" :step="0.01" :min="0" :max="999999.99" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付日期" prop="paymentDate">
              <el-date-picker clearable
                              v-model="form.paymentDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择支付日期"
                              style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
<!--              <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" style="width: 100%"/>-->
              <el-select v-model="form.paymentMethod" placeholder="请选择支付方式" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.rl_salary_payment"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-form-item label="税率" prop="taxRate">
          <el-input v-model="form.taxRate" placeholder="请输入税率" />
        </el-form-item>-->

        <el-row>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">
                      <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                    </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
  </div>
</template>

<script>
import { listSalary, getSalary, delSalary, addSalary, updateSalary } from "@/api/mes/rl/salary";
import UserSingleSelect from "@/components/userSelect/single.vue"
import ItemSelect from "@/components/itemSelect/multi.vue";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import {treeselect} from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Salary",
  components: {Treeselect, UserSingleSelect},
  dicts: ['rl_salary_payment'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 薪酬管理表格数据
      salaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/mes/rl/salary/importData"
      },
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: null,        payPeriod: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        employeeName: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" }
        ],        payPeriod: [
          { required: true, message: "薪酬周期不能为空", trigger: "blur" }
        ],        baseSalary: [
          { required: true, message: "基本工资不能为空", trigger: "blur" }
        ],        grossSalary: [
          { required: true, message: "应发工资不能为空", trigger: "blur" }
        ],        netSalary: [
          { required: true, message: "实发工资不能为空", trigger: "blur" }
        ],           socialInsurance: [
          { required: true, message: "社会保险不能为空", trigger: "blur" }
        ],        medicalInsurance: [
          { required: true, message: "医疗保险不能为空", trigger: "blur" }
        ],        paymentDate: [
          { required: true, message: "支付日期不能为空", trigger: "blur" }
        ],
        paymentMethod: [
          { required: true, message: "支付方式不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],

        salaryStatus: [
          { required: true, message: "支付状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();

  },
  watch: {
    // 监听相关字段的变化
    "form.baseSalary": "calculateGrossSalary",
    "form.commission": "calculateGrossSalary",
    "form.overtimePay": "calculateGrossSalary",
    "form.bonus": "calculateGrossSalary",
    "form.allowance": "calculateGrossSalary",
    "form.grossSalary": "calculateNetSalary",
      "form.socialInsurance": "calculateNetSalary",
      "form.medicalInsurance": "calculateNetSalary",
      "form.housingFund": "calculateNetSalary",
      "form.taxAmount": "calculateNetSalary",
    "form.deductions": "calculateNetSalary"
  },
  methods: {
    /** 查询薪酬管理列表 */
    getList() {
      this.loading = true;
      listSalary(this.queryParams).then(response => {
        this.salaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    calculateGrossSalary() {
      this.form.grossSalary = this.form.baseSalary +
        this.form.commission +
        this.form.overtimePay +
        this.form.bonus +
        this.form.allowance;
    },
    calculateNetSalary() {
      this.form.netSalary = this.form.grossSalary -
        this.form.socialInsurance -
        this.form.medicalInsurance -
        this.form.housingFund -
        this.form.taxAmount -
        this.form.deductions;
    },

    selectDept(node){
      console.log("11111",node)
      this.form.deptName=node.label
      console.log("22222",this.form.deptName)
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        // debugger;
        this.deptOptions = response.data;
      });
    },
    //点击人员选择按钮
    handleUserSelect(){
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row){
      this.form.employeeName= row.nickName;
      this.form.employeeId= row.userId;
      this.form.deptId=row.deptId
      this.form.deptName=row.dept.deptName
      this.$forceUpdate()
      console.log("1111",this.form.deptId)
      console.log("2222",this.form.deptName)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        salaryId: null,        employeeId: null,        employeeName: null,        payPeriod: null,
        baseSalary: null,        overtimePay: null,        bonus: null,        commission: null,
        allowance: null,        deductions: null,        grossSalary: null,        netSalary: null,
        taxRate: null,        taxAmount: null,        socialInsurance: null,        medicalInsurance: null,        housingFund: null,
        paymentDate: null,        paymentMethod: null,        salaryStatus: '未支付',        notes: null,
        createBy: null,        createTime: null,        updateBy: null,        updateTime: null  ,deptId:null,deptName:null    };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.salaryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.getTreeselect();
      this.open = true;
      this.title = "添加薪酬管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // this.getTreeselect();
      const salaryId = row.salaryId || this.ids
      getSalary(salaryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改薪酬管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.salaryId != null) {
            updateSalary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSalary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const salaryIds = row.salaryId || this.ids;
      this.$modal.confirm('是否确认删除薪酬管理编号为"' + salaryIds + '"的数据项？').then(function() {
        return delSalary(salaryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/rl/salary/export', {
        ...this.queryParams
      }, `salary_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "薪酬数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('mes/rl/salary/importTemplate', {
      }, `salary_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {

      this.$refs.upload.submit();
    }
  }
};
</script>
